package com.company.admin.service.user;

import com.company.admin.common.myException.BizException;
import com.company.admin.dao.user.CompanyAdminUserDao;
import com.company.admin.entity.User.AdminUserEntity;
import com.company.admin.req.user.UserLoginRequest;
import com.company.admin.resp.user.UserLoginResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 赵成林
 * @date 2019/2/16 21:08
 */
@Service
public class UserService {

    @Autowired
    private CompanyAdminUserDao companyAdminUserDao;

    /**
     * 目前没有注册，所以后端自己插入一个账号
     * @param adminUserEntity
     */
    @Transactional
    public void addAdminUser(AdminUserEntity adminUserEntity){
        adminUserEntity.setAdminUserName("admin");
        adminUserEntity.setAdminUserPassword("2345.net");
        adminUserEntity.setCreateTime(new Date());
        adminUserEntity.setToken(null);
        adminUserEntity.setUpdateTime(new Date());
        companyAdminUserDao.insert(adminUserEntity);
    }

    public AdminUserEntity getUserByToken(String token){
        return companyAdminUserDao.getAdminUserByToken(token);
    }

    /**
     * 登录
     * @param userLoginRequest
     * @return
     */
    public UserLoginResponse login(UserLoginRequest userLoginRequest){
        if (StringUtils.isBlank(userLoginRequest.getUserName())){
            throw new BizException(202, "用户名必须填写");
        }
        if (StringUtils.isBlank(userLoginRequest.getPassword())){
            throw new BizException(202, "登录密码必须填写");
        }
        AdminUserEntity adminUserEntity = companyAdminUserDao.getAdminUserByName(userLoginRequest.getUserName());
        if (adminUserEntity == null){
            throw new BizException(202, "该用户不存在");
        }
        if (!userLoginRequest.getPassword().equals(adminUserEntity.getAdminUserPassword())){
            throw new BizException(202,"密码错误");
        }
        // 如果登录成功，就去修改token；
        String token = userLoginRequest.getUserName() + new Date().getTime();
        int result = companyAdminUserDao.updateTokenById(token, adminUserEntity.getAdminUserId());
        if (result != 1){
            throw new BizException(202, "登录失败，请稍后重试");
        }
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        userLoginResponse.setLoginTime(new Date());
        userLoginResponse.setToken(token);
        userLoginResponse.setUserName(userLoginRequest.getUserName());
        return userLoginResponse;
    }
}
